package com.example.springbootrabbitmq.service.impl;

import com.example.springbootrabbitmq.constant.Constant;
import com.example.springbootrabbitmq.entity.MessageLog;
import com.example.springbootrabbitmq.entity.TOrder;
import com.example.springbootrabbitmq.mapper.MessageLogMapper;
import com.example.springbootrabbitmq.mapper.OrderMapper;
import com.example.springbootrabbitmq.producer.OrderSender;
import com.example.springbootrabbitmq.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootrabbitmq.utils.DateUtil;
import com.example.springbootrabbitmq.utils.FastJsonConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hl
 * @since 2020-06-09
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, TOrder> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MessageLogMapper messageLogMapper;

    @Autowired
    OrderSender orderSender;

    @Transactional(rollbackFor=Exception.class)
    @Override
    public void createOrder(TOrder TOrder) throws Exception{
        /**
         * 订单入库
         */
        Long orderTime = System.currentTimeMillis();
        orderMapper.insert(TOrder);

        /**
         * 消息入库
         */
        MessageLog messageLog = new MessageLog();
        messageLog.setId(TOrder.getMessageId());
        messageLog.setMessage(FastJsonConverUtil.objToJson(TOrder));
        messageLog.setStatus("0");
        messageLog.setNextTry(DateUtil.addMinutes(orderTime, Constant.ORDER_TIMEOU));
        messageLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
        messageLog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        messageLogMapper.insert(messageLog);

        /**
         * 发送消息
         */
        orderSender.sendOrder(TOrder);
    }
}
